package 二分查找;

public class Algo34 {

//    给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
//    如果数组中不存在目标值 target，返回 [-1, -1]。

    private static int[] result = {-1,-1};

    private static int[] searchRange(int[] nums, int target) {
        binarySearch1(nums, target);
        return result;
    }

    private static void binarySearch1(int[] nums, int target) {
        int left = 0, right = nums.length - 1;

        int indexL = -1, indexR = -1;

        while (left<=right) {
            int mid = left + (right - left) /2;
            if(nums[mid] > target) {
                right = mid - 1;
            }else if(nums[mid] <target) {
                left = mid + 1;
            }else if(nums[mid] == target) {
                indexR = mid;
                indexL = mid;
                break;
            }
        }

        if(indexL != -1) {
            while (indexL>=0 && nums[indexL] == target) {
                indexL--;
            }
            while (indexR<nums.length && nums[indexR] == target) {
                indexR++;
            }
            result[0] = indexL+1;
            result[1] = indexR-1;
        }
    }


    public static void main(String[] args) {
        int[] arr = {};
        System.out.println(searchRange(arr, 0).toString());
    }
}
